//理财直融
import React from 'react';
import { connect } from 'dva';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { message, Spin, Tooltip } from 'antd';
import { AdvancedSearch, DATA_ENTRY, ModalC, PrimaryC, TableC, ExportC } from '../../../../comps';
import myStyle from '../index.less';
import moment from 'moment';
//组件
import RightInfo from '../shareComp/rightInfo';
import TipsInfo from '../shareComp/tipInfo';
import MoneyLayer from './moneyLayer';
import { findValueByCode, formSelectData } from '../../../../utils/utils';
import uuid from 'es6-uuid';
const borrowerCodeList = ['1 - 住户', '2 - 广义政府', '3 - 非金融性企业', '4 - 金融机构（实体）', '5 - 特定目的载体', '6 - 境外'];

class MoneyDirectFinancial extends React.Component {
  constructor() {
    super();
    this.state = {
      selectedRowKeys: [], //选中的checkbox
      selectedRows: [], //选中项的详情
      searchObj: {}, //查询的条件
      currentPage: 1,
      numInPage: 10,
      total: 0,
      columns: [
        {
          title: '证券代码',
          key: 'tradingCode',
        },
        {
          title: '证券名称',
          key: 'secuabbr',
        },
        {
          title: '融资企业所在省',
          key: 'financeLocationProvince',
        },
        {
          title: '融资企业所在市',
          key: 'financeLocationCity',
        },
        {
          title: '融资企业所属行业',
          key: 'issuerIndustry',
        },
        {
          title: '发行机构类型(按规模划分)',
          key: 'issuerScale',
        },
        {
          title: '租户',
          key: 'tenant',
        },
        {
          title: '贷款担保方式',
          key: 'loanGuaranteeType',
        },
        {
          title: '地区',
          key: 'area',
        },
        {
          title: '地区代码',
          key: 'areaCode',
        },
        {
          title: '借款人代码',
          key: 'borrowerCode',
        },
        {
          title: '借款人类型',
          key: 'borrowerCodeType',
        },
        {
          title: '利率(%)',
          key: 'interestRate',
          type: 'rate',
        },
        {
          title: '起息日',
          key: 'startDate',
          type: 'date',
        },
        {
          title: '到期日',
          key: 'endDate',
          type: 'date',
        },
        {
          title: '贷款产品类别',
          key: 'loanProductType',
        },
        {
          title: '贷款实际投向',
          key: 'loanDirection',
        },
        {
          title: '利率是否固定',
          key: 'interestRateType',
        },
        {
          title: '贷款种类',
          key: 'loanType',
        },
        {
          title: '来源',
          key: 'originType',
        },
      ],
      dataSource: [],
      count: 0, //与资讯不一致的条数
      isReset: false, // 是否点击重置
      type: 'add', //目前点击的是新增的状态
      visiable: false, //弹窗
      LayerContent: null, //弹窗中的内容
      flag: '1', //1全部 2不一致 3无评级
      addedThisMonth: 0, //本月新增条数
      isHistory: false, //是否是历史日期
      holdDataList: [], //持仓日期下拉
      latestholdDate: '', //最新的持仓日期
      filteredInfo: null, //筛选信息 受控
    };
  }
  componentDidMount() {
    const {
      globalM: { dataDictionary = {} },
    } = this.props;
    this.props.dispatch({
      type: 'manMoneyDirectFinancialM/save',
      payload: {
        dataDictionary,
      },
    });
    //查询持仓日期
    this.props.dispatch({
      type: 'bondInformationM/queryHoldDataList',
      payload: {},
      callback: (data) => {
        if (data) {
          let temp = [];
          data.map((item) => {
            temp.push({
              value: item,
              title: item,
            });
          });
          //设置默认值为最新的持仓日期 其余下拉日期为历史日期
          this.AdvancedSearchRef?.props.form?.setFieldsValue({
            holdDate: data.length ? data[0] : undefined,
          });
          let obj = this.state.searchObj;
          obj.holdDate = data.length ? data[0] : undefined;
          this.setState(
            {
              holdDataList: [...temp],
              searchObj: { ...obj },
              latestholdDate: data.length ? data[0] : undefined, ////保存最新的持仓
            },
            () => {
              this.getTableData();
            },
          );
        } else {
          this.setState({ holdDataList: [] });
        }
      },
    });
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.tenant != this.props.tenant) {
      this.getTableData();
    }
  }
  //查询
  onQuery = (e) => {
    //如果子查询还在 不可以点击查询按钮
    if (this.state.flag != '1') {
      message.warning('请点击与资讯不一致提示语句，取消查询后重试！');
      return;
    }
    // 判断是历史数据还是当前数据
    if (this.AdvancedSearchRef) {
      if (this.state.latestholdDate != this.AdvancedSearchRef.props.form.getFieldValue('holdDate')) {
        this.setState({
          flag: '1', //历史数据 永远查询全部
        });
      }
      this.setState({
        isHistory: this.state.latestholdDate == this.AdvancedSearchRef.props.form.getFieldValue('holdDate') ? false : true,
      });
    }
    this.setState(
      {
        searchObj: e,
        currentPage: 1,
        numInPage: 10,
        isReset: false,
      },
      () => {
        this.getTableData();
      },
    );
  };
  //重置
  onClear = () => {
    this.setState({
      isReset: true,
      filteredInfo: null, //重置清除筛选条件
      originType: undefined,
    });
    //重置日期
    this.AdvancedSearchRef?.props.form?.setFieldsValue({
      holdDate: this.state.latestholdDate,
    });
    //租户也重置
    this.props.resetTenant();
  };
  //表格分页切换
  handleTableChange = (pagination, filters) => {
    const { current, pageSize } = pagination;
    const { isReset } = this.state;
    if (isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      this.setState({
        filteredInfo: { originType: [] },
        originType: undefined,
      });
      return;
    }
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
        filteredInfo: filters,
        originType: filters?.originType?.length ? filters.originType.join(',') : undefined,
      },
      () => {
        this.getTableData();
      },
    );
  };
  // 获取表格数据
  getTableData = () => {
    const { currentPage, numInPage, searchObj, originType } = this.state;
    this.setState(
      {
        dataSource: [],
        selectedRowKeys: [],
        selectedRows: [],
      },
      () => {
        this.props.dispatch({
          type: 'manMoneyDirectFinancialM/getDataList',
          payload: {
            ...searchObj,
            currentPage: currentPage,
            numInPage: numInPage,
            flag: this.state.flag,
            originType, //来源
            tenant: this.props.tenant, //点击跳转页 就是查询原
          },
          callback: (data) => {
            if (data?.dataSource?.length) {
              data.dataSource.map((item) => {
                (item.originFlag = item.originType > 1 ? false : true), (item.key = uuid(16));
              });
            }
            if (data) {
              this.setState({
                dataSource: data.dataSource || [],
                total: data.pageInfo && data.pageInfo.total ? data.pageInfo.total : 0,
                addedThisMonth: data.addedThisMonth || 0,
                count: data.count || 0,
              });
            }
          },
        });
      },
    );
  };

  //新增
  add = () => {
    this.setState({
      visiable: true,
      type: 'add',
      LayerContent: null,
    });
  };
  //批量确认
  confirm = () => {
    const { dispatch } = this.props;
    //点击批量确认的时候，前端需要判断有几条数据待补充，并且做出提示
    if (this.state.selectedRows.filter((item) => item.isSuppleInfo == '1')?.length) {
      message.warning(`你有${this.state.selectedRows.filter((item) => item.isSuppleInfo == '1').length}条信息待补充`);
      return false;
    }
    dispatch({
      type: 'manMoneyDirectFinancialM/confirmData',
      payload: {
        data: this.state.selectedRowKeys,
      },
      callback: (res) => {
        if (res) {
          this.getTableData();
        }
      },
    });
  };
  //点击编辑出现弹窗
  handleFn = (record) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'manMoneyDirectFinancialM/getDetail',
      payload: {
        id: record?.id,
      },
      callback: (res) => {
        if (res) {
          this.setState({
            LayerContent: res,
          });
        } else {
          this.setState({
            LayerContent: null,
          });
        }
        this.setState({
          visiable: true,
          type: 'edit',
        });
      },
    });
  };
  //删除onDelete
  onDelete = (id) => {
    this.props.dispatch({
      type: 'manMoneyDirectFinancialM/deleteById',
      payload: { id },
      callback: () => {
        message.success('删除成功!');
        //删除成功 刷新列表
        this.getTableData();
      },
    });
  };
  //改变列
  handleColumns = (columns) => {
    let { filteredInfo } = this.state;
    const {
      globalM: {
        dataDictionary: { LOAN_DIRECTION_DICT = [] },
      },
    } = this.props;
    filteredInfo = filteredInfo || {};
    if (columns && columns.length) {
      if (columns[columns.length - 1].title != '操作' && !this.state.isHistory) {
        columns.push({
          title: '操作',
          dataIndex: 'operate',
          key: 'operate',
          type: 'operate',
          fixed: 'right',
          operates: [
            {
              title: '编辑',
              onClick: (record, index) => {
                this.handleFn(record);
              },
              rules: {
                disabled: {
                  relation: 'or',
                  items: [
                    {
                      key: 'isConfirm',
                      value: ['1'],
                      relation: ['='],
                    },
                  ],
                },
              },
            },
            {
              title: '删除',
              onClick: (record) => {
                this.onDelete(record.id);
              },
              rules: {
                disabled: { relation: 'or', items: [{ key: 'originFlag', value: [true], relation: ['='] }] },
              },
            },
          ],
        });
      }
      if (columns.length) {
        columns.map((item, index) => {
          //来源
          if (item.key == 'originType') {
            item.type = 'filterCol';
            (item.filters = (this.props.manMoneyDirectFinancialM.dataDictionary?.ORIGIN_TYPE_DICT || []).map((item) => {
              return { text: item.value, value: item.code };
            })),
              (item.filterMultiple = true);
            (item.filteredValue = filteredInfo.originType || null),
              (item.render = (text, record) => {
                return findValueByCode(text, this.props.manMoneyDirectFinancialM.dataDictionary?.ORIGIN_TYPE_DICT || []);
              });
          }
          if (item.key == 'issuerIndustry') {
            item.render = (text, record) => {
              let arrs = this.props.manMoneyDirectFinancialM.dataDictionary?.GJTJJHYFLI?.filter((item) => item.code == text);
              return (arrs?.length && arrs[0].value) || (text ? text : '--');
            };
          }
          if (item.key == 'issuerScale') {
            item.render = (text, record) => {
              let arrs = this.props.manMoneyDirectFinancialM.dataDictionary?.ISSUER_BY_SIZE?.filter((item) => item.code == text);
              return (arrs?.length && arrs[0].value) || (text ? text : '--');
            };
          }
          if (item.key == 'loanGuaranteeType') {
            item.title = () => {
              return (
                <div>
                  {' '}
                  贷款担保方式
                  <Tooltip
                    title={
                      <div>
                        <div>D – 信用/免担保贷款</div>
                      </div>
                    }
                  >
                    <QuestionCircleOutlined style={{ paddingLeft: '5px' }} />
                  </Tooltip>
                </div>
              );
            };
          }
          if (item.key == 'borrowerCodeType') {
            item.title = () => {
              return (
                <div>
                  {' '}
                  借款人类型
                  <Tooltip
                    title={
                      <div>
                        {borrowerCodeList.map((item, key) => {
                          return <div key={key}>{item}</div>;
                        })}
                      </div>
                    }
                  >
                    <QuestionCircleOutlined style={{ paddingLeft: '5px' }} />
                  </Tooltip>
                </div>
              );
            };
          }
          if (item.key == 'loanProductType') {
            item.title = () => {
              return (
                <div>
                  {' '}
                  贷款产品类别
                  <Tooltip
                    title={
                      <div>
                        <div>F99 – 其他贷款</div>
                      </div>
                    }
                  >
                    <QuestionCircleOutlined style={{ paddingLeft: '5px' }} />
                  </Tooltip>
                </div>
              );
            };
          }
          if (item.key == 'loanDirection') {
            item.title = () => {
              return (
                <div>
                  {' '}
                  贷款实际投向
                  <Tooltip
                    title={
                      <div className={myStyle.tip}>
                        {formSelectData(LOAN_DIRECTION_DICT).map((item, key) => {
                          return <div key={key}>{item.value + ' - ' + item.title}</div>;
                        })}
                      </div>
                    }
                  >
                    <QuestionCircleOutlined style={{ paddingLeft: '5px' }} />
                  </Tooltip>
                </div>
              );
            };
          }
          if (item.key == 'interestRateType') {
            item.title = () => {
              return (
                <div>
                  {' '}
                  利率是否固定
                  <Tooltip
                    title={
                      <div>
                        <div>
                          RF01 – 固定利率
                          <br />
                          RF02 – 其他
                        </div>
                      </div>
                    }
                  >
                    <QuestionCircleOutlined style={{ paddingLeft: '5px' }} />
                  </Tooltip>
                </div>
              );
            };
          }
          if (item.key == 'loanType') {
            item.title = () => {
              return (
                <div>
                  {' '}
                  贷款种类
                  <Tooltip
                    title={
                      <div>
                        <div>3 – 其他债权</div>
                      </div>
                    }
                  >
                    <QuestionCircleOutlined style={{ paddingLeft: '5px' }} />
                  </Tooltip>
                </div>
              );
            };
          }
        });
      }
      return [...columns];
    }
  };
  //改变勾选
  onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedRowKeys, selectedRows });
  };
  //弹窗点击确认
  onOk = () => {
    const { type, LayerContent } = this.state;
    const { dispatch } = this.props;
    this.content.getFormData((res) => {
      let params = null;
      if (type == 'add') {
        if (res?.tradeContent?.tradingCode) {
          params = {
            ...res,
            tradingCode: res?.tradeContent?.tradingCode,
          };
        } else {
          params = {
            ...res,
            tradingCode: res?.tradeContent,
          };
        }
      } else {
        params = {
          ...res,
          tradingCode: res?.tradingCode,
          id: LayerContent?.id,
        };
      }
      if (params.tradeContent) delete params.tradeContent;
      dispatch({
        type: 'manMoneyDirectFinancialM/saveData',
        payload: params,
        callback: (res) => {
          if (res) {
            this.setState(
              {
                visiable: false,
              },
              () => {
                //清空表单
                setTimeout(() => {
                  this.content.reset();
                }, 300);
                //需要是否是历史持仓 需要为是才可以展示
                this.getTableData();
              },
            );
          }
        },
      });
    });
  };
  //弹窗点击取消
  onCancel = () => {
    this.setState(
      {
        visiable: false,
      },
      () => {
        //清空表单
        setTimeout(() => {
          this.content.reset();
        }, 300);
      },
    );
  };
  //点击了提示语
  tipClick = (flag) => {
    this.setState(
      {
        flag: flag == true ? '2' : '1',
      },
      () => {
        this.setState(
          {
            isReset: false, // 是否点击重置
            selectedRowKeys: [], // 表格checkbox选择
            selectedRows: [], // 表格checkbox选择
            isBatchConfirmation: false, // 批量确认按钮置灰
            currentPage: 1,
          },
          () => {
            this.getTableData();
          },
        );
      },
    );
  };
  render() {
    const { originType, LayerContent, searchObj, columns, dataSource, currentPage, total, numInPage, selectedRowKeys, visiable, type, count } = this.state;
    const { confirmLoading, loading, saveLoading } = this.props;
    let newColumns = this.handleColumns(_.cloneDeep(columns)) || [];
    const dataSourceQuery = [
      {
        dataIndex: 'codeName',
        title: '代码或名称',
        type: DATA_ENTRY.INPUT,
        allowClear: true,
      },
      {
        dataIndex: 'isConfirm',
        title: '是否已确认',
        isTrueFalseJudge: true,
        type: DATA_ENTRY.SELECT,
        allowClear: true,
      },
      {
        dataIndex: 'holdDate',
        title: '持仓日期',
        type: DATA_ENTRY.SELECT,
        allowClear: false,
        dataSource: this.state.holdDataList || [],
      },
    ];
    //多选框
    const rowSelection = {
      selectedRowKeys: selectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: (record) => ({
        disabled: record.isConfirm == '1' || record.isSuppleInfo == '1',
      }),
    };
    return (
      <div>
        <AdvancedSearch onRef={(ref) => (this.AdvancedSearchRef = ref)} dataSource={dataSourceQuery} onQuery={this.onQuery} onClear={this.onClear}></AdvancedSearch>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '20px' }}>
          <div style={{ display: 'flex', alignContent: 'center' }}>
            {!this.state.isHistory && (
              <div>
                <PrimaryC title='新增' onClick={this.add}></PrimaryC>
              </div>
            )}
            {!this.state.isHistory && (
              <div style={{ marginLeft: '16px', marginRight: '16px' }}>
                <PrimaryC title='批量确认' onClick={this.confirm} loading={confirmLoading} disabled={!selectedRowKeys?.length}></PrimaryC>
              </div>
            )}
            <div style={{ marginRight: '20px' }}>
              <ExportC
                url={'gateway/instrument-server/financingRegulation/financingExport'}
                search={{ ...searchObj, flag: this.state.flag, tenant: this.props.tenant, originType: originType ?? '' }}
                disabled={dataSource?.length ? false : true}
              />
            </div>
            {!this.state.isHistory && (
              <div style={{ display: 'flex' }}>
                <TipsInfo count={count} handleClick={this.tipClick}></TipsInfo>
              </div>
            )}
          </div>
          {!this.state.isHistory && (
            <div style={{ display: 'flex' }}>
              <RightInfo redTitle={`本月新增标的${this.state.addedThisMonth || 0}只`}></RightInfo>
            </div>
          )}
        </div>
        <div style={{ marginTop: '16px' }}>
          <TableC
            columns={newColumns}
            dataSource={dataSource}
            current={currentPage}
            total={total}
            pageSize={numInPage}
            rowKey='key'
            scroll={{ x: 'max-content' }}
            onChange={this.handleTableChange}
            rowSelection={!this.state.isHistory ? rowSelection : undefined}
            loading={loading}
            rowClassName={(record) => {
              return record.createTs == this.state.latestholdDate ? myStyle.redCls : '';
            }}
          ></TableC>
        </div>
        <ModalC
          visible={visiable}
          onOk={this.onOk}
          onCancel={this.onCancel}
          title={type == 'add' ? '新增' : '编辑'}
          width={960}
          confirmLoading={saveLoading || this.props.modalLoading == true}
          destroyOnClose={false}
          maskClosable={false}
        >
          <Spin spinning={this.props.queryLoading == true}>
            <MoneyLayer type={type} borrowerCodeList={borrowerCodeList} LayerContent={LayerContent} onRef={(ref) => (this.content = ref)}></MoneyLayer>
          </Spin>
        </ModalC>
      </div>
    );
  }
}
export default connect(({ loading, manMoneyDirectFinancialM, bondInformationM, globalM }) => ({
  loading: loading.effects['manMoneyDirectFinancialM/getDataList'],
  confirmLoading: loading.effects['manMoneyDirectFinancialM/confirmData'],
  saveLoading: loading.effects['manMoneyDirectFinancialM/saveData'],
  queryLoading: loading.effects['manMoneyDirectFinancialM/getDetail'],
  modalLoading: loading.effects['manMoneyDirectFinancialM/getTradeDetail'],
  manMoneyDirectFinancialM,
  bondInformationM,
  globalM,
}))(MoneyDirectFinancial);
